package com.example.java.base.jdk8.stringJoiner;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * JoinerTest:
 *
 * @author Administrator
 * @date 2021/02/25
 */
public class JoinerTest {
    /**
     * 待操作的数据
     *
     * @return 待操作的数据
     */
    public static List<String> data() {
        List<String> ids = new ArrayList<>();
        ids.add("鲁班七号");
        ids.add("诸葛亮");
        ids.add("王昭君");
        return ids;
    }

    /**
     * 常规拼接把集合的数据通过,拼接
     */
    @Test
    public void test1() {
        StringBuilder sb = new StringBuilder();
        for (String id : data()) {
            if (sb.length() > 0) {
                sb.append(",");
            }
            sb.append(id);
        }
        System.out.println(sb);
    }

    /**
     * 使用JDK8 String.join
     */
    @Test
    public void test2() {
        System.out.println(String.join(",", data()));
    }

    /**
     * 将元素按照 分隔符 前缀 后缀 元素添加进去并格式化
     */
    @Test
    public void test3() {
        StringJoiner sj = new StringJoiner(",", "{", "}");
        sj.add("first").add("second").add("third");
        System.out.println(sj.toString());
    }

    /**
     * 结合JDK8的stream，可以拼接列表元素
     */
    @Test
    public void test4() {
        List<String> numbers = data();
        System.out.println(numbers.stream().map(Object::toString).collect(Collectors.joining(",")));
    }

}
